import { getAIResponse } from './ai_response';

export function chooseImage(page) {
  wx.chooseImage({
    count: 1,
    success: (res) => {
      const tempFilePaths = res.tempFilePaths;
      uploadImage(tempFilePaths[0], page);
    },
    fail: (err) => {
      wx.showToast({
        title: '选择图片失败',
        icon: 'none',
      });
      console.error('Choose image failed:', err);
    },
  });
}

function uploadImage(filePath, page) {
  wx.uploadFile({
    url: 'https://open.oppomobile.com/agentplatform/app_api/plugins/files/upload', // 替换为图片上传接口地址
    filePath: filePath,
    name: 'file',
    formData: {
      user: wx.getStorageSync('userInfo').userId // 获取用户唯一标识
    },
    header: {
      'Authorization': 'Bearer Rfl0IQuZR9vBT75i' // 替换为实际的认证令牌
    },
    success: (res) => {
      const data = JSON.parse(res.data);
      if (data.code === '0000') {
        const imageUrl = data.data.url;
        page.setData({
          previewImageUrl: imageUrl, // 将图片URL设为预览URL
          sendIcon: 'https://kangkangkangkang.oss-cn-wuhan-lr.aliyuncs.com/%E5%BA%B7/chat/%E5%8F%91%E9%80%81.png', // 更改为发送图标
        });
      } else {
        wx.showToast({
          title: '图片上传失败',
          icon: 'none',
        });
      }
    },
    fail: (err) => {
      wx.showToast({
        title: '图片上传失败',
        icon: 'none',
      });
      console.error('Image upload failed:', err);
    },
  });
}


export function previewImage(event, page) {
  const current = event.target.dataset.src;
  const urls = page.data.messages.filter(item => item.isImage).map(item => item.content);
  wx.previewImage({
    current: current,
    urls: urls,
  });
}

export function removePreview(page) {
  page.setData({
    previewImageUrl: '' // 移除预览图片URL
  });
}
